import * as THREE from '../../build/three.module.js';
import Stat from '../../jsm/libs/stats.module.js';

let windowHalfX = innerWidth / 2,
    windowHalfY = innerHeight / 2,
    mouseX = 0,
    mouseY = 0,
    root;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);

const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 15000);
camera.position.set(0, 0, 500);

const gmt = new THREE.BoxBufferGeometry(100, 100, 100);
const mtl = new THREE.MeshNormalMaterial();

root = new THREE.Mesh(gmt, mtl);
// root.position.x = 1000;
scene.add(root);

const amount = 200;
let obj, parent = root;

for(let i = 0; i < amount; i += 1) {
  obj = new THREE.Mesh(gmt, mtl);
  obj.position.x = 100;
  
  parent.add(obj);
  parent = obj;
}

parent = root;

for(let i = 0; i < amount; i += 1) {
  obj = new THREE.Mesh(gmt, mtl);
  obj.position.x = -100;

  parent.add(obj);
  parent = obj;
}

parent = root;

for(let i = 0; i < amount; i += 1) {
  obj = new THREE.Mesh(gmt, mtl);
  obj.position.y = -100;

  parent.add(obj);
  parent = obj;
}

parent = root;

for(let i = 0; i < amount; i += 1) {
  obj = new THREE.Mesh(gmt, mtl);
  obj.position.y = 100;

  parent.add(obj);
  parent = obj;
}

parent = root;

for(let i = 0; i < amount; i += 1) {
  obj = new THREE.Mesh(gmt, mtl);
  obj.position.z = -100;

  parent.add(obj);
  parent = obj;
}

parent = root;

for(let i = 0; i < amount; i += 1) {
  obj = new THREE.Mesh(gmt, mtl);
  obj.position.z = 100;

  parent.add(obj);
  parent = obj;
}

const axesH = new THREE.AxesHelper(1000);
scene.add(axesH);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const stats = new Stat();
document.body.appendChild(stats.dom);

const render = () => {
  const time = Date.now() * .001;

  const rx = Math.sin(time * .7) * .2,
        ry = Math.sin(time * .3) * .2,
        rz = Math.sin(time * .2) * .2;

  camera.position.x += (mouseX - camera.position.x) * .05;
  camera.position.y += (-mouseY - camera.position.y) * .05;

  camera.lookAt(scene.position);

  root.traverse(mesh => {
    mesh.rotation.x = rx;
    mesh.rotation.y = ry;
    mesh.rotation.z = rz;
  });

  renderer.render(scene, camera);
}

const animate = () => {
  requestAnimationFrame(animate);

  stats.update();
  render();
}
animate();

//事件绑定
const handleWindowResize = () => {
  windowHalfX = innerWidth / 2;
  windowHalfY = innerHeight / 2;

  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize);

const handleMouseMove = (e) => {
  mouseX = (e.clientX - windowHalfX) * 10;
  mouseY = (e.clientY - windowHalfY) * 10;
}
document.addEventListener('mousemove', handleMouseMove);